/**
 * Copyright © 2013 南京思创信息技术有限公司. *
 * 版权所有.
 *
 * 类名　　    : Loading
 * 功能概要    : 欢迎页面. * 做成日期    : 2013/06/04 wangxw
 */
package com.sevenit.nj.yrmtfish.login;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.telephony.TelephonyManager;
import android.view.KeyEvent;

import com.sevenit.nj.yrmtfish.R;
import com.sevenit.nj.yrmtfish.common.MemConfig;
import com.sevenit.nj.yrmtfish.common.AppManager;
import com.sevenit.nj.yrmtfish.common.FileBase;
import com.sevenit.nj.yrmtfish.common.ServerMaster;
import com.sevenit.nj.yrmtfish.common.StaticPara;
import com.sevenit.nj.yrmtfish.common.Utils;

/**
 * 欢迎页面的类
 * @author wangxw
 * @version 1.0
 */
@SuppressLint("HandlerLeak") 
public class Loading extends Activity {

	///////定义画面专有消息////////
	//进入免责条款画面.
	final int MSG_PAGE_README = 1;
	//进入设置画面.
	final int MSG_PAGE_SETTING = 2;
	
	//当面画面名
	private String _strPageName;
	
	//请求服务器方法
	private ServerMaster _server;

	//是否显示免责条款画面.
	private boolean bShowReadme = false;

	/**
	 * onCreate
	 */
	public void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);
		
		//设置画面布局
		this.setContentView(R.layout.loading);
		
		//添加该Activity到AppManager
		AppManager.addActivity(this);

		//装载全局数据.
		loadUserData();
		
		//初始化全局数据.
		initUserData();
		
		//初始化画面数据.
		initPageData();
		
		//线程装载数据
		sendMsg(StaticPara.MSG_PAGE_LOADING);
	}
	
	/**
	 * 装载全局数据.
	 */
	private void loadUserData() {
		
		/* 读取程序配置文件 */
		FileBase fb = new FileBase();
		fb.openAppConf();
		
		// 心跳包频率（单位：秒）
		String strSpeed = fb.getAppConfValue("HEART_BEAT_SPEED");
		if(Utils.isHalfNum(strSpeed)){
			StaticPara.HeartBeatSpeed = Integer.parseInt(strSpeed);
		}
		
		/* 读取内存配置文件 */
		StaticPara.MemConf = new MemConfig(this);
		StaticPara.MemConf.getMemConf();
		
		/* 初始化SD卡 */
		StaticPara.SdDir = fb.getSdDir();
		
		//检查SD卡是否可以使用
		if(!Utils.isNull(StaticPara.SdDir) && 
			fb.createDir(StaticPara.getSdImgDir()) &&
			fb.createDir(StaticPara.getSdTmpDir())){
			StaticPara.bSdCanUse = true;
		}
	}
	
	/**
	 * 初始化全局数据.
	 */
	private void initUserData() {

		/* 内存配置文件数据 */
		
		//是否显示readme画面
		if(StaticPara.MemConf.bShowReadme){
			bShowReadme = true;
		}
		
		//手机GID
		if(Utils.isNull(StaticPara.MemConf.PhoneId)){
			//获取手机ID
			TelephonyManager tm =((TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE));
			StaticPara.MemConf.PhoneId = tm.getDeviceId();
			StaticPara.MemConf.saveMemConf();
		}
		
		//用户登录状态.
		if(!StaticPara.isLogin()){
			StaticPara.MemConf.UserSta = StaticPara.USER_STA_OFFLINE;
		}
	}
	
	/**
	 * 初始化画面数据.
	 */
	private void initPageData() {
		//初始化画面名
		_strPageName = this.getClass().getName();
		
		//初始化全局对象
		_server = new ServerMaster(this, StaticPara.MemConf.AppServerIp, StaticPara.MemConf.AppServerPort);
	}
	
	/**
	 * 新线程查询数据.
	 * @author wangxw
	 */
	class LoadThread implements Runnable {
		
		public void run() {
			
			if(!_server.netState()){
				//网络不可用.
				sendMsg(StaticPara.MSG_ERR_NET);
			}else {
				//免责条款画面.
				goPageReadme();
			}
			//else {
			//	//主菜单画面.
			//	goPageMenu();
			//}
		}
		
		/**
		 * 进入免责条款画面.
		 */
		public void goPageReadme() {
			try{
				Thread.sleep(2000);
			}catch(Exception e){
				
			}
			Intent intent = new Intent();
			intent.setClass(Loading.this, Readme.class);
			startActivity(intent);
			AppManager.closePage(Loading.class.getName());
		}
		
		/**
		 * 进入设置画面.
		 */
		public void goPageSetting() {
			try{
				Thread.sleep(2000);
			}catch(Exception e){
				
			}
			//Intent intent = new Intent();
			//intent.setClass(Loading.this, Setting.class);
			//startActivity(intent);
			AppManager.closePage(Loading.class.getName());
		}
		
		/**
		 * 进入主菜单画面.
		 */
		public void goPageMenu() {
			try{
				Thread.sleep(2000);
			}catch(Exception e){
			}
			//Intent intent = new Intent();
			//intent.setClass(Loading.this, MainMenu.class);
			//startActivity(intent);
			AppManager.closePage(Loading.class.getName());
		}
	}

	/**
	 * 向界面发送消息.
	 * UI显示动作不能在线程里做.
	 */
	private void sendMsg(int Msg){
		Message message = new Message();
		Bundle bundle = new Bundle();
		bundle.putInt(_strPageName, Msg);
		message.setData(bundle);
		myHandler.sendMessage(message);
	}
	
	//主线程消息处理.
	Handler myHandler = new Handler() {
		public void handleMessage(Message msg) {
			int iMsg = msg.getData().getInt(_strPageName);
			switch (iMsg) {
			
			case StaticPara.MSG_ERR_NET:
				AlertDialog.Builder builder = new AlertDialog.Builder(Loading.this); 
		        builder.setMessage("当前网络不可用，\r\n请检查网络是否正常连接！"); 
		        builder.setTitle("发生错误"); 
		        builder.setPositiveButton("确定", 
		                new android.content.DialogInterface.OnClickListener() { 
		                    @Override 
		                    public void onClick(DialogInterface dialog, int which) { 
		                        dialog.dismiss(); 
		                        AppManager.sysExit();
		                    } 
		                }); 
		        builder.create().show();
				break;
			case StaticPara.MSG_PAGE_LOADING:
				(new Thread(new LoadThread())).start();
				break;
			default:
				
			}
			
			super.handleMessage(msg);
		}
	};

	/**
	 * 监听手机硬件上的返回等按钮
	 */
	@Override 
    public boolean onKeyDown(int keyCode, KeyEvent event) { 
        if (keyCode == KeyEvent.KEYCODE_BACK &&	event.getRepeatCount() == 0) { 
            dialog(); 
            return false; 
        }
        return false; 
    }
	
	/**
	 * 退出确认.
	 */
	private void dialog() { 
        AlertDialog.Builder builder = new AlertDialog.Builder(this); 
        builder.setMessage("确定要退出吗?"); 
        builder.setTitle("提示"); 
        builder.setPositiveButton("确定", 
                new android.content.DialogInterface.OnClickListener() { 
                    @Override 
                    public void onClick(DialogInterface dialog, int which) { 
                        dialog.dismiss();
                        AppManager.sysExit();
                    } 
                }); 
        builder.setNegativeButton("取消", 
                new android.content.DialogInterface.OnClickListener() { 
                    @Override 
                    public void onClick(DialogInterface dialog, int which) { 
                        dialog.dismiss(); 
                    } 
                }); 
        builder.create().show(); 
    }
}
